#include <stdio.h>
#include "ses_button.h"

// callback functions
pButtonCallback rotary_Button = NULL;
pButtonCallback joystic_Button = NULL;

void button_init() {

	DDR(BUTTON_ROTARY_PORT) &= ~(1 << BUTTON_ROTARY_PIN);
	DDR(BUTTON_JOYSTICK_PORT) &= ~(1 << BUTTON_JOYSTICK_PIN);

	BUTTON_ROTARY_PORT |= (1 << BUTTON_ROTARY_PIN);
	BUTTON_JOYSTICK_PORT |= (1 << BUTTON_JOYSTICK_PIN);
	PCICR |= (1 << PCIE0);

	PCMSK0 |= (1 << BUTTON_ROTARY_PIN);
	PCMSK0 |= (1 << BUTTON_JOYSTICK_PIN);

}

void button_setRotaryButtonCallback(pButtonCallback callback) {
	rotary_Button = callback;
}

void button_setJoystickButtonCallback(pButtonCallback callback) {
	joystic_Button = callback;
}

/*
 * Interrupt service routine for pin change interrupt 7:0.
 *
 * After one of the if-clauses is true, the *_triggered flag is set to true and
 * therefore disables further triggers. This is important for debouncing the
 * buttons. The flag will be set to false again when function *_pressed() is
 * called.
 */ISR(PCINT0_vect) {

	if (rotary_Button) {
		PCICR &= ~(1 << PCIE0);
		rotary_Button();
	}

	if (joystic_Button) {
		PCICR &= ~(1 << PCIE0);
		joystic_Button();
	}

}

bool rotary_pressed() {
	PCICR |= (1 << PCIE0);
	return ((PIN(BUTTON_ROTARY_PORT) & (1 << BUTTON_ROTARY_PIN)) == 0);
}

bool joystick_pressed() {
	PCICR |= (1 << PCIE0);
	return ((PIN(BUTTON_JOYSTICK_PORT) & (1 << BUTTON_JOYSTICK_PIN)) == 0);
}

